<!--
 * @Author: Bennty
 * @Date: 2024-12-05 17:08:11
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2025-01-16 16:49:31
 * @Description: 请填写简介
-->
<template>
    <div class="p-2">
        <transition
            :enter-active-class="proxy?.animate.searchAnimate.enter"
            :leave-active-class="proxy?.animate.searchAnimate.leave"
        >
            <div class="search">
                <span class="configure-name">{{ configureDetail.combinationName }}</span>
                <el-button type="danger" plain icon="Back" @click="handleClickBack">返回上级</el-button>
            </div>
        </transition>
        <el-card shadow="never" :body-style="{minHeight: '90vh', paddingBottom: '50px'}">
            <el-row class="pannels" :gutter="20">
                <el-col class="left-pannel form-container" :span="16">
                    <div class="selected-auxiliarys">
                        <el-row :gutter="20">
                            <el-col :span="6" v-for="auxiliary,index in auxiliariesList" :key="auxiliary.productId">
                                <div class="selected-auxiliary">
                                    <div class="delete-auxiliary" @click="handleDeleteAuxiliary(index)"></div>
                                    <el-image class="auxiliary-image" :src="auxiliary.imageUrl"></el-image>
                                    <span class="auxiliary-name">{{ auxiliary.specsDetail }}</span>
                                    <span class="auxiliary-info">{{ `${auxiliary.specialFlag == '1'?'专版':'非专版'}  数量：${auxiliary.number}` }}</span>
                                </div>
                                
                            </el-col>
                        </el-row>
                    </div>
                    <div class="order-form">
                        <el-form ref="formRef" :model="formData" >
                            <el-row :gutter="10">
                                <el-col :span="18">
                                    <el-row :gutter="15">
                                        <el-col :span="6">
                                            <el-form-item label="销售渠道" prop="saleMethod">
                                                <el-select v-model="formData.saleMethod" placeholder="请选择" >
                                                    <el-option v-for="item in sale_method" :key="item.value" :value="item.value" :label="item.label"></el-option>
                                                </el-select>
                                            </el-form-item>
                                        </el-col>
                                        <el-col :span="6">
                                            <el-form-item label="付款方式" prop="paymentMethod">
                                                <el-select v-model="formData.paymentMethod" placeholder="请选择" >
                                                    <el-option v-for="item in pay_type" :key="item.value" :value="item.value" :label="item.label"></el-option>
                                                </el-select>
                                            </el-form-item>
                                        </el-col>
                                        <el-col :span="6">
                                            <el-form-item label="订单单价" prop="price">
                                                <el-input type="number" v-model.number="formData.price" placeholder="请输入"></el-input>
                                            </el-form-item>
                                        </el-col>
                                        <el-col :span="6">
                                            <el-form-item label="旺旺名称" prop="wwName">
                                                <el-input type="text" v-model="formData.wwName" placeholder="请输入"></el-input>
                                            </el-form-item>
                                        </el-col>
                                    </el-row>
                                    <el-row :gutter="15">
                                        <el-col :span="6">
                                            <el-form-item label="客户名称" prop="customerId">
                                                <el-select v-model="formData.customerId" placeholder="请选择" >
                                                    <el-option v-for="item in customerList" :key="item.id" :value="item.id" :label="item.customerName"></el-option>
                                                </el-select>
                                            </el-form-item>
                                        </el-col>
                                        <el-col :span="6">
                                            <el-form-item label="人数配比" prop="personCount">
                                                <el-select v-model="formData.personCount" placeholder="请选择" >
                                                    <el-option v-for="item in personal_ratio" :key="item.value" :value="item.value" :label="item.label"></el-option>
                                                </el-select>
                                            </el-form-item>
                                        </el-col>
                                        <el-col :span="6">
                                            <el-form-item label="包装方式" prop="packingMethod">
                                                <el-select v-model="formData.packingMethod" placeholder="请选择" >
                                                    <el-option v-for="item in package_method" :key="item.value" :value="item.value" :label="item.label"></el-option>
                                                </el-select>
                                            </el-form-item>
                                        </el-col>
                                        <el-col :span="6">
                                            <el-form-item label="组装工费" prop="assemblePrice">
                                                <el-input type="number" v-model.number="formData.assemblePrice" placeholder="请输入"></el-input>
                                            </el-form-item>
                                        </el-col>
                                    </el-row>
                                    <el-row :gutter="15">
                                        <el-col :span="6">
                                            <el-form-item label="订单编号" prop="orderId">
                                                <el-input v-model="formData.orderId" placeholder="请输入"></el-input>
                                            </el-form-item>
                                        </el-col>
                                        <el-col :span="6">
                                            <el-form-item label="订单数量" prop="number">
                                                <el-input v-model.number="formData.number" placeholder="请输入"></el-input>
                                            </el-form-item>
                                        </el-col>
                                        <el-col :span="6">
                                            <el-form-item label="发货方式" prop="deliveryMethod">
                                                <el-select v-model="formData.deliveryMethod" placeholder="请选择" >
                                                    <el-option v-for="item in send_type" :key="item.value" :value="item.value" :label="item.label"></el-option>
                                                </el-select>
                                            </el-form-item>
                                        </el-col>
                                        <el-col :span="6">
                                            <el-form-item label="包装工费" prop="packingPrice">
                                                <el-input type="number" v-model.number="formData.packingPrice" placeholder="请输入"></el-input>
                                            </el-form-item>
                                        </el-col>
                                    </el-row>
                                    <el-row :gutter="15">
                                        <el-col :span="8">
                                            <el-form-item label="订单总价">
                                                {{ amount }}
                                            </el-form-item>
                                        </el-col>
                                        <el-col :span="8">
                                            <el-form-item label="制单日期">
                                                {{ nowDate }}
                                            </el-form-item>
                                        </el-col>
                                        <el-col :span="8">
                                            <el-form-item label="交货日期">
                                                <el-date-picker v-model="formData.deliveryDate" type="date" placeholder="请选择" :disabled-date="(date:Date)=>setDateLimit(date,7)" format="YYYY-MM-DD" :value-format="'YYYY-MM-DD'" />
                                            </el-form-item>
                                        </el-col>
                                    </el-row>
                                    <el-form-item label="备注" prop="remark">
                                        <el-input v-model="formData.remark" type="textarea" maxlength="125" show-word-limit placeholder="请输入"></el-input>
                                    </el-form-item>
                                </el-col>
                                
                                <el-col :span="6" style="position: relative">
                                    <div class="placeOrder-container">
                                        <el-form-item label="所属公司">A公司</el-form-item>
                                        <el-form-item>
                                            <el-button class="place-order" @click="handleClickSubmit">确定下单</el-button>
                                        </el-form-item>
                                    </div>
                                </el-col>
                            </el-row>
                        </el-form>
                    </div>
                </el-col>
                <el-col :span="8" class="right-pannel auxiliary-container">
                    <div class="col-title">
                        <span >通用部件：</span>
                    </div>
                    <div class="auxiliarys" v-for="item in configureData" :key="item.productSubcategoryName">
                        <span class="auxiliary-subCatagory">{{item.productSubcategoryName}}</span>
                        <el-row style="padding: 20px" :gutter="20">
                            <el-col :span="8" v-for="auxiliary in item.children" :key="auxiliary.specsDetail">
                                <div class="auxiliary" @click="handleClickAuxiliary(auxiliary)">
                                    <el-image class="auxiliary-image" fit="fill" :src="auxiliary.imageUrl"></el-image>
                                    <span class="auxiliary-name">{{ auxiliary.specsDetail }}</span>
                                </div>
                            </el-col>
                        </el-row>
                    </div>
                </el-col>
            </el-row>
        </el-card>
        <selectAuxiliary :visible="selectAuxiliaryVisible" :auxiliary="auxiliaryDetail" @close="handleCloseSelect" @submit="handleSubmitSelect" />
    </div>
</template>

<script setup lang="ts">
import { type FormInstance } from 'element-plus';
import { Form } from '@/api/sj/productManagement/customizedOrder/types';
import { getConfigureDataApi,getConfigureDetailApi } from '@/api/sj/productManagement/productConfigure';
import { listCustomer } from '@/api/sj/customer';
import { addCustomizedOrderApi } from '@/api/sj/productManagement/customizedOrder/index';
import { getNowDate, setDateLimit } from '@/utils/dateFormat';
import selectAuxiliary from './selectAuxiliary.vue';
import useTagsViewStore from "@/store/modules/tagsView";
import './orderDetails.scss';

const formRef = ref<FormInstance>();
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { sale_method,pay_type,personal_ratio,package_method,send_type } = toRefs<any>(proxy?.useDict('sale_method', 'pay_type','personal_ratio','package_method','send_type'));
const router = useRouter();
const type = ref(router.currentRoute.value.params.type);
const configureId = ref(router.currentRoute.value.params.id);
const configureDetail = ref<any>({});
const configureData = ref<any[]>([]);
const customerList = ref<any[]>([]);
const selectAuxiliaryVisible = ref(false);
const auxiliaryDetail = ref<any>();
const auxiliariesList = ref<any[]>([]);
const nowDate = ref(getNowDate());
const amount = ref<number>(0);

const formData = ref<Form>({
    saleMethod: undefined,
    paymentMethod: undefined,
    price: undefined,
    wwName: undefined,
    customerId: undefined,
    packingMethod: undefined,
    assemblePrice: undefined,
    orderId: undefined,
    number: undefined,
    deliveryMethod: undefined,
    packingPrice: undefined,
    personCount: undefined,
    deliveryDate: undefined
});
const visitedViews = computed(() => useTagsViewStore().visitedViews);

/** 点击回到上级 */
const handleClickBack = () => {
    // console.log('visitedViews', visitedViews.value);
    // console.log(router.currentRoute.value);
    let pageIndex = undefined;
    const currentPage = visitedViews.value.filter((item: any,index: number)=>{
        if(item.path == router.currentRoute.value.fullPath){
            pageIndex = index;
        };
        return item.path == router.currentRoute.value.fullPath
    })[0];
    if(pageIndex){
        //@ts-ignore
        proxy?.$tab.closeOpenPage(visitedViews.value[pageIndex-1].fullPath)
    };
};

const getConfigureData = async () => {
    const {code, data} = await getConfigureDataApi(configureId.value);
    if(code == 200){
        configureData.value = data;
    };
};

const getConfigureDetail =  async () => {
    const {code, data} = await getConfigureDetailApi(configureId.value);
    if(code == 200){
        configureDetail.value = data;
    };
};

const getCustomerData = async () => {
    const { code, rows } = await listCustomer({pageSize: 999, pageNum: 1});
    if(code == 200){
        customerList.value = rows;
    }
};

/** 选择配件 */
const handleClickAuxiliary = (auxiliary: any) => {
    selectAuxiliaryVisible.value = true;
    auxiliaryDetail.value = auxiliary;
};

const handleCloseSelect = () => {
    selectAuxiliaryVisible.value = false;
};

/** 提交选择的配件 */
const handleSubmitSelect = (auxiliary: any) => {
    let isExist = false;
    let auxiliaryIndex = null;
    for(let i = 0; i<auxiliariesList.value.length;i++){
        if(auxiliariesList.value[i].productCategoriesType == auxiliary.productCategoriesType){
            if(auxiliariesList.value[i].productSubcategoryType == auxiliary.productSubcategoryType){
                isExist = true;
                auxiliaryIndex = i;
                break;
            };
        };
    };
    if(isExist && auxiliaryIndex != null){
        auxiliariesList.value[auxiliaryIndex] = auxiliary;
    }else{
        auxiliariesList.value.push(auxiliary);
    }
};

/** 删除选择的配件 */
const handleDeleteAuxiliary = (index: number) => {
    auxiliariesList.value.splice(index, 1);
};

/** 计算订单总价 */
watch(()=>[formData.value.number, formData.value.price, formData.value.assemblePrice, formData.value.packingPrice],([newNumber, newPrice,newAssemblePrice,newPackingPrice])=>{
    const unitePrice = (newPrice || 0) + (newAssemblePrice || 0) + (newPackingPrice || 0);
    const totalNumber = newNumber || 0;
    amount.value = unitePrice * totalNumber;
});

/** 提交新增订单 */
const handleClickSubmit = async () => {
    const dataList = auxiliariesList.value.map((item:any)=>{
        return {
            ...item,
            customizedProductId: configureId.value
        }
    });
    const submitData = {
        ...formData.value,
        productType: type.value,
        dataList: [...dataList],
        productStyle: configureDetail.value.productStyle,
        combinationId: configureId.value
    };
    const {code} = await addCustomizedOrderApi(submitData);
    if(code == 200){
        proxy?.$modal.msgSuccess('添加订单成功');
        handleClickBack();
    };
};

onMounted(()=>{
    getConfigureData();
    getConfigureDetail();
    getCustomerData();
});
</script>

<style lang="scss" scoped>
</style>